﻿var express = require('express');
var app = express();
var path = require('path');
var router_red = express.Router();
var router_blue = express.Router();
var logintest = express.Router();
var login = express.Router();
var ejs = require('ejs');
var axios = require('axios');
var request = require('request');
app.use(express.static('./'));
app.set("views", '/view');
app.set('views', path.join(__dirname, 'views'));
app.engine('html',ejs.__express);
app.set('view engine', 'html');

var session = require('express-session');
var cookieParser = require('cookie-parser');
app.use(cookieParser("keyboard cat"));
app.use(session({
	secret: 'keyboard cat',
	cookie: {maxAge: 800000 },
	resave: false,
	saveUninitialized: true
}));

router_red.get('/', function(req, res, next) {
	res.render('red');
});
router_blue.get('/', function(req, res, next) {
	console.log("sssssss");
	res.status(302);
	res.render('blue');
});
login.get('/', function(req, res, next) {
	res.render('login');
});

//headers:req.headers
app.post('/dologin', function(req, res, next) {
	/*
	req.session.user = {name:"xxx",id:"yyy"};
	console.log(res);
	if(req.session.user){
		res.json({status:200,user:req.session.user});//正常
	}else{
		res.json({status:401});//未登录
	}
	*/
	request('http://localhost:2002/dologin',{} ,function (error, response, body) {
		if (!error && response.statusCode == 200) {
			var data=JSON.parse(response.body);
			console.log(response.headers);
			res.headers=response.response;
			if(data.status==200){
				res.json(data);
			}else{
				res.json(data);
			}
		}else{
			console.log(error);
			console.log(response.statusCode);
			res.json({status:500});
		}
	})
});
app.use('/logintest',function(req,res,next){
	/*
	console.log(req.session);
	if(req.session.user){
		res.json({status:200,info:"登录成功",user:req.session.user});
	}else{
		res.json({status:401,info:"未登录"});//未登录
	}
	*/
	request('http://localhost:2002/logintest',{} ,function (error, response, body) {
		console.log(response);
		if (!error && response.statusCode == 200) {
			var data=JSON.parse(response.body);
			if(data.status==200){
				res.json(data);
			}else{
				res.json(data);
			}
		}else{
			console.log(error);
			console.log(response.statusCode);
			res.json({status:500});
		}
	})
});
app.use('/logout',function(req,res,next){
	request('http://localhost:2002/logout',{} ,function (error, response, body) {
		if (!error && response.statusCode == 200) {
			var data=JSON.parse(response.body);
			if(data.status==200){
				res.json(data);
			}else{
				res.json(data);
			}
		}else{
			console.log(error);
			console.log(response.statusCode);
			res.json({status:500});
		}
	})
});

app.use('/red',router_red);
app.use('/blue',router_blue);
app.use('/login',login);

var server = app.listen(2001, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Example app listening at http://%s:%s', host, port);
});
